package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        UserLoginVO userLoginVO = new UserLoginVO();



       //思路:
        // 拿到openid（微信官方服务器发送请求）

        CloseableHttpClient httpClient = HttpClients.createDefault();
        Map<String, String> paramMap =new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        String jsonstr = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);

        JSONObject jsonobject = JSON.parseObject(jsonstr);
        String openid = jsonobject.getString("openid");
        //判断一下用户是否成功授权了，openid是否成功拿到
        if (openid==null){
           throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断是否为新用户（数据库select openid）
        User user =userMapper.selectByOpenid(openid);
        if (user==null)//新用户，完成插入（注册）
        {
            user=User.builder()
                     .openid(openid)
                      .createTime(LocalDateTime.now())
                      . build();
            userMapper.insert(user);//注册
        }

            String authentication =createJWT(user.getId());//jwt令牌的内容给到这个变量（变量名字与前端商量好了）
            userLoginVO.setId(user.getId());
            userLoginVO.setToken(authentication);
            userLoginVO.setOpenid(openid);





        return userLoginVO;
    }

    private String  createJWT(Long id) //user表的主键id
    {
        Map<String, Object> clams=new HashMap<>();
        clams.put(JwtClaimsConstant.USER_ID,id);//这个地方在校验jwt令牌是否正确的时候会用到key的名字
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), clams);
        return jwt;
    }
}
